package com.zhiche.wms.service.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.lisa.json.JSONUtil;
import com.zhiche.wms.configuration.MyConfigurationProperties;
import com.zhiche.wms.core.supports.RestfulResponse;
import com.zhiche.wms.core.supports.enums.InterfaceAddrEnum;
import com.zhiche.wms.core.supports.enums.InterfaceEventEnum;
import com.zhiche.wms.core.supports.enums.SystemEnum;
import com.zhiche.wms.core.utils.HttpClientUtil;
import com.zhiche.wms.core.utils.redislog.RedisLogUtil;
import com.zhiche.wms.service.dto.OTMEvent;
import com.zhiche.wms.service.dto.ProcessCallBack;
import com.zhiche.wms.service.dto.ShipParamDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * Created by zhaoguixin on 2018/7/26.
 */
@Component
public class BusinessNodeExport {

    private static final Logger LOGGER = LoggerFactory.getLogger(BusinessNodeExport.class);

    @Autowired
    private MyConfigurationProperties properties;

    /**
     * 导出事件至OTM
     *
     * @param otmEvent 事件
     * @return 请求ID
     */
    public String exportEventToOTM(OTMEvent otmEvent) {
        new Thread(() -> {
            //添加推送日志到日志系统
            addExportLogs(otmEvent, InterfaceAddrEnum.EVENT_URI.getAddress(), 1);
        }).start();

        String result = HttpClientUtil.postJson(
                properties.getIntegrationhost() + InterfaceAddrEnum.EVENT_URI.getAddress(),
                null,
                JSON.toJSONString(otmEvent),
                properties.getSocketTimeOut());
        if (!StringUtils.isEmpty(result)) {
            RestfulResponse<String> restfulResponse = JSON.parseObject(result,
                    new TypeReference<RestfulResponse<String>>() {
                    });
            if (Objects.nonNull(restfulResponse) && restfulResponse.getCode() == 0) {
                return restfulResponse.getData();
            }
        }
        return null;
    }

    /**
     * 添加日志记录到日志系统
     */
    public void addExportLogs(OTMEvent otmEvent, String uri, Integer dataStatus) {
        try {
            if (Objects.nonNull(otmEvent)) {

                String dtoJson = JSONUtil.toJsonStr(otmEvent);
                RedisLogUtil.addExportLogs(SystemEnum.WMS.getCode(), SystemEnum.INTEGRATION.getCode(), otmEvent.getEventType(), uri, otmEvent.getShipmentId(),
                        otmEvent.getOrderReleaseId(), otmEvent.getVin(), otmEvent.getOrderReleaseId(), otmEvent.getExportKey(), dtoJson, 1, dataStatus,"", Boolean.valueOf(properties.getLogRedisIsTest()));

//                String tableIdx = RedisLogTypeEnum.EVENT_EXPORT.getCode();
//                String sourceSystem = SystemEnum.WMS.getCode();
//                String targetSystem = SystemEnum.INTEGRATION.getCode();
//                // 来源、目标系统表示
//                // 目标API标示
//                String key = sourceSystem + "_" + targetSystem;
//                String fKey = uri + SystemEnum.UNDERLINE.getCode() + otmEvent.getExportKey() + SystemEnum.UNDERLINE.getCode() + otmEvent.getEventType() + SystemEnum.UNDERLINE.getCode() + dataStatus;
//                String dtoJson = JSONUtil.toJsonStr(otmEvent);
//                // 业务相关实体类
//                LogExportPo logExportPo = new LogExportPo(sourceSystem, targetSystem, otmEvent.getEventType(), uri, otmEvent.getShipmentId(),
//                        otmEvent.getOrderReleaseId(), otmEvent.getVin(), otmEvent.getOrderReleaseId(), otmEvent.getExportKey(), dtoJson, 1, "", 0, 0, dataStatus);
//                SysLogDataPo sysLogDataPo = new SysLogDataPo(tableIdx, JSONUtil.toJsonStr(logExportPo));
//                SysLogUtil.addSysLogs(key, fKey, sysLogDataPo, Boolean.valueOf(properties.getLogRedisIsTest()));
            }
        } catch (Exception e) {
            LOGGER.error("事件导出至otm，添加日志异常" + e.getMessage());
        }
    }

    /**
     * 得到异步处理结果
     *
     * @param requestId 请求ID
     */
    public ProcessCallBack getProcessResult(String requestId) {
        Map<String, String> params = new HashMap<>();
        params.put("requestId", requestId);
        String result = HttpClientUtil.post(
                properties.getIntegrationhost() + InterfaceAddrEnum.PROCESS_RESULT_URI.getAddress(),
                params,
                properties.getSocketTimeOut());
        if (!StringUtils.isEmpty(result)) {
            RestfulResponse<ProcessCallBack> restfulResponse = JSON.parseObject(result,
                    new TypeReference<RestfulResponse<ProcessCallBack>>() {
                    });
            if (Objects.nonNull(restfulResponse) && restfulResponse.getCode() == 0) {
                return restfulResponse.getData();
            }
        }
        return null;
    }

    public String exportEventToOTMNew (ShipParamDTO paramDTO) {
        new Thread(() -> {
            //添加推送日志到日志系统
            addExportLogs(paramDTO, InterfaceAddrEnum.EVENT_URI.getAddress(), 1);
        }).start();
        String result = HttpClientUtil.postJson(
                properties.getIntegrationhost() + InterfaceAddrEnum.EVENT_URI.getAddress(),
                null,
                JSON.toJSONString(paramDTO),
                properties.getSocketTimeOut());
        if (!StringUtils.isEmpty(result)) {
            RestfulResponse<String> restfulResponse = JSON.parseObject(result,
                    new TypeReference<RestfulResponse<String>>() {
                    });
            if (Objects.nonNull(restfulResponse) && restfulResponse.getCode() == 0) {
                return restfulResponse.getData();
            }
        }
        return null;
    }

}
